import { getToken } from './tokenStorage';
import { API_BASE_URL } from '../../constants/api';

// 存储特殊会话令牌 (如果后端实现了临时解决方案)
let sessionToken: string | null = null;
let sessionTokenExpiry: number = 0;

/**
 * 获取有效的API会话令牌
 * 如果现有令牌已过期，将自动刷新
 */
export async function getValidSessionToken(): Promise<string | null> {
  // 直接返回存储的认证令牌，与web端保持一致
  const authToken = await getToken();
  return authToken;
}

/**
 * 获取有效的API认证头
 */
export async function getApiHeaders(contentType: string = 'application/json'): Promise<Record<string, string>> {
  const token = await getValidSessionToken();
  
  if (!token) {
    return {};
  }
  
  const headers: Record<string, string> = {
    'Authorization': `Bearer ${token}`,
  };
  
  console.log('获取API请求头:', headers);

  if (contentType) {
    headers['Content-Type'] = contentType;
  }
  
  return headers;
}

/**
 * 封装的API请求函数
 * @param endpoint API端点路径
 * @param method HTTP方法
 * @param body 请求体
 * @param customHeaders 自定义请求头
 * @returns 解析后的JSON响应
 */
export async function apiRequest<T = any>(
  endpoint: string, 
  method: string = 'GET', 
  body: any = null,
  customHeaders: Record<string, string> = {}
): Promise<T> {
  // 获取带有认证信息的请求头
  let headers = await getApiHeaders();
  
  // 合并自定义请求头
  headers = { ...headers, ...customHeaders };
  
  console.info('请求头:', headers);
  if (!Object.keys(headers).length) {
    throw new Error('未授权，请先登录');
  }
  
  const options: RequestInit = {
    method,
    headers
  };
  
  if (body) {
    if (body instanceof FormData) {
      // 对于FormData，不设置Content-Type，让浏览器自动设置
      delete (headers as any)['Content-Type'];
      options.body = body;
    } else {
      options.body = JSON.stringify(body);
    }
  }
  
  // 发送请求
  let response = await fetch(`${API_BASE_URL}${endpoint}`, options);
  
  // 如果返回401，可能是令牌已过期，尝试清除会话令牌并重新获取
  if (response.status === 401) {
    console.log('令牌已过期，尝试刷新...');
    // 清除会话令牌缓存
    sessionToken = null;
    sessionTokenExpiry = 0;
    
    // 重新获取头部
    headers = await getApiHeaders();
    if (Object.keys(headers).length) {
      options.headers = { ...headers, ...customHeaders };
      // 重试请求
      response = await fetch(`${API_BASE_URL}${endpoint}`, options);
    }
  }
  
  // 检查响应状态
  if (!response.ok) {
    let errorMessage = `API请求失败: ${response.status}`;
    
    try {
      // 尝试解析错误响应
      const errorData = await response.text();
      errorMessage = `${errorMessage} - ${errorData}`;
    } catch (e) {
      // 忽略解析错误
    }
    
    throw new Error(errorMessage);
  }
  
  // 解析并返回响应
  return response.json() as Promise<T>;
}

/**
 * 处理FormData请求的特殊函数
 */
export async function apiFormRequest<T = any>(
  endpoint: string,
  formData: FormData,
  method: string = 'POST'
): Promise<T> {
  // 对FormData请求不设置Content-Type
  const headers = await getApiHeaders('');
  delete headers['Content-Type'];
  console.log('headers1111111', headers);
  return apiRequest<T>(endpoint, method, formData, headers);
}

/**
 * 获取用户列表
 */
export async function fetchUsers(query: string = ''): Promise<any> {
  return apiRequest('/api/users/search?query=' + encodeURIComponent(query), 'POST', []);
}

/**
 * 创建报销主题
 */
export async function createTheme(
  themeName: string, 
  themeContent: string, 
  participants: Array<{ userId: string, role: string }>
): Promise<any> {
  const formData = new FormData();
  formData.append('theme_name', themeName);
  formData.append('theme_content', themeContent);
  formData.append('participants', JSON.stringify(participants));
  
  return apiFormRequest('/api/themes/save', formData);
} 